package com.xiaozhichao.jarslink.main.config;

import com.alipay.jarslink.api.ModuleConfig;
import com.alipay.jarslink.api.impl.AbstractModuleRefreshScheduler;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ModuleScanner {

    private static String SNAPSHOT = "SNAPSHOT";
    public static Map<String,List<String>> doScan(String path) throws IOException {
        File files = new File(path);
        if(files.exists()){
            File[] lists = files.listFiles(new FileFilter(){
                @Override
                public boolean accept(File pathname) {
                    String name = pathname.getName();
                    if(pathname.isFile() && name.endsWith(".jar")){
                        return true;
                    }
                    return false;
                }
            });
            if (lists.length<=0) {
                return null;
            }
            Map<String,List<String>> modules = new HashMap<>();
            for(File file : lists){
                ModuleConfig moduleConfig = new ModuleConfig();
                String jarName = file.getName();
                String name_version = jarName.substring(0, jarName.length() - 4);
                int index = -1;
                if (name_version.toUpperCase().endsWith("SNAPSHOT")) {
                    index = name_version.substring(0, name_version.length() - 9).lastIndexOf("-");
                } else {
                    index = name_version.lastIndexOf("-");
                }
                String moduleName = name_version.substring(0, index);
                String moduleVersion = name_version.substring(index + 1);

                List<String> infos = new ArrayList<>(3);
                infos.add(file.getPath());
                infos.add(moduleName);
                infos.add(moduleVersion);
                if(modules.containsKey(moduleName)){
                    if(Double.valueOf(modules.get(moduleName).get(2).substring(0,moduleVersion.indexOf(SNAPSHOT)-1))
                            < Double.valueOf(moduleVersion.substring(0,moduleVersion.indexOf(SNAPSHOT)-1))){
                        modules.put(moduleName,infos);
                    }
                }else{
                    modules.put(moduleName,infos);
                }
            }
            return modules;
        }
        return null;
    }

    public static void main(String[] args) {
        String moduleVersion = "1.2-SNAPSHOT";
        System.out.println(moduleVersion.substring(0,moduleVersion.indexOf(SNAPSHOT)-1));
    }
}
